package com.lagou.edu.consumer;

import com.lagou.edu.decoder.RpcDecoder;
import com.lagou.edu.encoder.RpcEncoder;
import com.lagou.edu.handler.ClientHandler;
import com.lagou.edu.request.RpcRequest;
import com.lagou.edu.response.RpcResponse;
import com.lagou.edu.serializer.JSONSerializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 赵虎
 * @date 2020/11/25 12:06
 */
public class RpcConsumer {
    private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    private static ClientHandler client;


    private static void initClient() throws InterruptedException {
        client = new ClientHandler();

        NioEventLoopGroup group = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();

        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new RpcDecoder(RpcResponse.class,new JSONSerializer()));
                        pipeline.addLast(new RpcEncoder(RpcRequest.class,new JSONSerializer()));
                        pipeline.addLast(client);
                    }
                });

        bootstrap.connect("localhost", 8081).sync();
    }

    public Object createProxy(final Class<?> clazz) {

        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{clazz}, (proxy, method, args) -> {
            if (client == null) {
                initClient();
            }
            RpcRequest request = new RpcRequest();
            request.setClassName(clazz.getSimpleName());
            request.setMethodName(method.getName());
            request.setParameters(args);
            request.setParameterTypes(method.getParameterTypes());
            request.setResultTypes(method.getReturnType());
            client.setRpcRequest(request);
            return executor.submit(client).get();
        });
    }
}
